package net.oschina.simpleplus.dao.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import net.oschina.simpleplus.dao.UserDao;
import net.oschina.simpleplus.entity.User;
import net.oschina.simpleplus.util.ClazzUtil;

@Repository
public class UserDaoImpl implements UserDao{
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public void insertNewUser(User user){
		if(jdbcTemplate.update("insert into user(email, password, nick_name, head_img, salt)values(?, ?, ?, ?, ?)", 
				new Object[]{
						user.getEmail(),
						user.getPassword(),
						user.getNickName() == null ? "" : user.getNickName(),
						user.getHeadImg() == null ? "" :user.getHeadImg(),
						user.getSalt()
								}) > 0){
			user.setId(jdbcTemplate.queryForObject("select id from user where email = ? ", new Object[]{user.getEmail()},( rs, r) -> {return rs.getInt(1);}));
		}
	}

	@Override
	public User findUserByEmail(String email) {
		return jdbcTemplate.queryForObject("select * from user where email = ?" , new Object[]{email}, (rs, r) -> {
			return ClazzUtil.extraData(rs, User.class);
		});
	}
}
